<?php
namespace app\app\controller;
use think\Db;
class Express extends Common
{
    //获取附近的司机  Express/nearby_list
    public function nearby_list()
    {
        $lng = request()->request('lng');
        $lat = request()->request('lat');
        $area = request()->request('area');
        $msg['state'] = 0;
        $msg['data'] = [];
        if(empty($lng) || empty($lat)){
            $msg['msg'] = '经纬度缺失';
        }else{
            $msg['state'] = 1;
            $aid = Db::table('area')->where('name','like','%'.$area.'%')->value('id');
            $scope = Db::table('express_config')->where('aid',$aid)->value('scope');//区域限制
            $pi = floatval($this->get_lat_lng($scope));
            $this_time=time();
            $sql = 'select id as express_id,lng,lat,aid from user where status=1 and express_type=1 and business=1 and isExpress=1 and active_time>'.($this_time-300).' and lat > '.$lat.'-'.$pi.' and lat < '.$lat.'+'.$pi.' and lng > '.$lng.'-'.$pi.' and lng < '.$lng.'+'.$pi.' order by ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.'* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
            $data= Db::table('user')->query($sql);
            $msg['data']=$data;
            $msg['msg'] = '获取成功';

        }
        return json($msg);
    }

//    //获取图标
//    public function get_icon()
//    {
//        $area = !empty(request()->request('area'))?request()->request('area'):'郓城县';
//        $aid = Db::table('area')->where('name','like','%'.$area.'%')->value('id');
//        $msg['state'] = 1;
//        $msg['data'] = Db::table('express_config')->field('express_icon,icon_status')->where('aid',$aid)->find();
//        $msg['msg'] = '获取成功';
//        return json($msg);
//    }

//    //上传经纬度
//    public function upload_location()
//    {
//        $token = request()->request('token');
//        $uid = token_decode($token);
//        $lng = request()->request('lng');
//        $lat = request()->request('lat');
//        $province = request()->request('province');
//        $city = request()->request('city');
//        $area = request()->request('area');
//        $data['lng'] = $lng;
//        $data['lat'] = $lat;
//        if($province != '' && $city != '' && $area != ''){
//            $data['pid'] = Db::table('province')->where('name','like','%'.$province.'%')->value('id');
//            $data['cid'] = Db::table('city')->where('name','like','%'.$city.'%')->value('id');
//            $data['aid'] = Db::table('area')->where('name','like','%'.$area.'%')->value('id');
//        }
//        $data['active_time'] = time();
//        $msg['state'] = 0;
//        $msg['data'] = '';
//        if(empty($lng) || empty($lat)){
//            $msg['msg'] = '经纬度缺失';
//        }else{
//            $msg['state'] = 1;
//            Db::table('user')->where('id',$uid)->update($data);
//            $msg['msg'] = '上传成功';
//        }
//        return json($msg);
//    }

//    //司机切换接单状态 Express/set_business
//    public function set_business()
//    {
//        $token = request()->request('token');
//        $uid = token_decode($token);
//        $status = request()->request('status');
//        $msg['state'] = 0;
//        $msg['data'] = $status;
//        if($status == ''){
//            $msg['msg'] = '参数错误';
//        }else{
//            $msg['state'] = 1;
//            Db::table('user')->where('id',$uid)->update(['business'=>$status]);
//            $msg['msg'] = 'success';
//        }
//        return json($msg);
//    }


//    //获取抢单列表
//    public function get_grab_order_list()
//    {
//        $token = request()->request('token');
//        $uid = token_decode($token);//司机
//        $area = request()->request('area');
//        $lng = request()->request('lng');
//        $lat = request()->request('lat');
//        //$status=request()->request("status");
//        $msg['state'] = 0;
//        $msg['data'] = [];
//        if(empty($lng) || empty($lat)){
//            $msg['msg'] = '经纬度缺失';
//        }else{
//            $msg['state'] = 1;
//            $aid = Db::table('area')->where('name','like','%'.$area.'%')->value('id');
//            $express_config =  Db::table('express_config')->where('aid',$aid)->find();
//            $scope = $express_config['scope'];
//            $pi = floatval($this->get_lat_lng($scope));
//            $fields = 'order_id,ident,cate_id,type,price,express_charge,place_lng,place_lat,place_phone,place_name,place_truename,place_address,target_lng,target_lat,target_phone,target_name,target_truename,target_address,remark,image1,image2,image3,audio,issue_time,receive_time,complete_time,shop_charge,tip,express_charge,express_get_money,flag,audio_length,require_time,status';
//            $express = Db::table('user')->where('id',$uid)->find();
//            $whereIn = Db::table('express_type_order')->where('express_type',$express['express_type'])->value('order_type');
//            $whereOr = '(target_lat > '.$lat.'-'.$pi.' and target_lat < '.$lat.'+'.$pi.' and target_lng > '.$lng.'-'.$pi.'and target_lng < '.$lng.'+'.$pi.') or (place_lat > '.$lat.'-'.$pi.' and place_lat < '.$lat.'+'.$pi.' and place_lng > '.$lng.'-'.$pi.' and place_lng < '.$lng.'+'.$pi.')';
//            $data = Db::table('order')->field($fields)->where(['status'=>1,'uid'=>['<>',$uid]])->where('express',0)->where($whereOr)->whereIn('type',$whereIn)->order('flag desc,issue_time desc')->select();
//            $msg['data'] = $data;
//            $msg['msg'] = '获取成功';
//        }
//        return json($msg);
//    }

    /**
    *  抢单(司机)
    **/
//    public function grab_order()
//    {
//        $token = request()->request('token');
//        $uid = token_decode($token);
//        $order_id = request()->request('order_id');
//        $check = Db::table('user')->where(['id'=>$uid,'isExpress'=>1,'business'=>1])->count();
//        $msg['state'] = 0;
//        $msg['data'] = '';
//        if($check == 0){
//            $msg['msg'] = '对不起，您暂时不能接单';
//        }else{
//            if(empty($order_id)){
//                $msg['msg'] = 'order_id is not have';
//            }else{
//                $order = Db::table('order')->where('order_id',$order_id)->find();
//                if(!empty($order['express'])){
//                    $msg['msg'] = '手慢了一步，订单已被抢走啦';
//                }else{
//                    $msg['state'] = 1;
////                    $express =Db::table('user')->where('id',$uid)->find();
////                    $data['express_get_money'] = ($order['express_charge']-($order['express_charge']*($express['express_cut']/100)))+($order['tip']-($order['tip']*($express['tip_cut']/100)))+$order['discount_money'];
////                    $data['system_money'] = $order['price'] - $data['express_get_money'];
//                    $data['express'] = $uid;
//                    $data['status'] = 3;//进行中
//                    $data['receive_time'] = time();
//                    Db::table('order')->where('order_id',$order_id)->update($data);
//                    //push 用户/司机
//                    push(md5($order['uid']),json_encode(['type'=>1,'message'=>'您的订单已被接单','parameters'=>$order_id,'status'=>5]));
//                    insert_message($order['uid'],'订单提醒','您的订单已被接单',5,$order_id);
//
//                    $msg['msg'] = '抢单成功';
//                }
//            }
//        }
//        return json($msg);
//    }


    //司机使用帮助
    public function get_use_help()
    {
        $content = '<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><title>使用帮助</title>';
        return $content.Db::table('notice')->where('title','司机使用帮助')->value('content');
    }

    /**
    *  放弃订单
    */
    public function abandon_order()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $order_id = request()->request('order_id');
        $date = date("Y-m-d");
        $check = Db::table('abandon_record')->where(['uid'=>$uid,'date'=>$date])->count();
        $msg['state'] = 0;
        $msg['data'] = '';
        $order = Db::table('order')->where('order_id',$order_id)->find();
        if($order['express'] != $uid){
            $msg['msg'] = '非法操作';
        }else{
            if($check >= 3){
                $msg['msg'] = '您今天已经取消过三次订单了，无法继续取消！';
            }else{
                $msg['state'] = 1;
                Db::table('order')->where(['express'=>$uid,'order_id'=>$order_id])->update(['express'=>'','express_get_money'=>'','status'=>2]);
                Db::table('abandon_record')->insert(['uid'=>$uid,'order_id'=>$order_id,'date'=>$date]);

                push(md5($order['uid']),json_encode(['type'=>1,'message'=>'您的订单被配送员取消接单','parameters'=>$order_id,'status'=>5]));
                insert_message($order['uid'],'订单提醒','您的订单被配送员取消接单',5,$order_id);

                $msg['msg'] = '取消成功';
            }
        }
        return json($msg);
    }

    //获取订单列表
    public function get_order_list()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $status = request()->request('status');
        $where['express'] = $uid;
        if(!empty($status)){
            $where['status'] = $status;
        }
        $msg['state'] = 1;
        $page = request()->request('page')?request()->request('page'):1;
        $pagesize = request()->request('pagesize')?request()->request('pagesize'):10;
        $fields = 'order_id,ident,cate_id,type,price,place_lng,place_lat,place_phone,place_name,place_truename,place_address,target_lng,target_lat,target_phone,target_name,target_truename,target_address,remark,image1,image2,image3,audio,issue_time,receive_time,complete_time,status,shop_charge,tip,express_charge,express_get_money,flag,discount,audio_length,require_time,status';
        $data = Db::table('order')->field($fields)->where($where)->page($page,$pagesize)->order('flag desc,issue_time desc')->select();
        foreach ($data as $k => $v){
            if(!empty($v['discount'])){
                $discount_info = Db::table('user_discounts')->where('id',$v['discount'])->find();
                $data[$k]['discount_type'] = $discount_info['type'];
                $data[$k]['discount_minus'] = $discount_info['minus'];
            }else{
                $data[$k]['discount_type'] = '';
                $data[$k]['discount_minus'] = '';
            }

        }
        $msg['data'] = $data;
        $msg['msg'] = '获取成功';
        return json($msg);
    }

    /**
     *  完成订单
     */
    public function complete_order()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $order_id = request()->request('order_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if(empty($order_id)){
            $msg['msg'] = '参数错误';
        }else{
            $order = Db::table('order')->where(['order_id'=>$order_id,'express'=>$uid])->find();
            if(count($order) > 0){
             
                   $msg['state'] = 1;
                   // $express_config = Db::table('express_config')->where('aid',$order['aid'])->find();
                    Db::table('order')->where(['express'=>$uid,'order_id'=>$order_id])->update(['status'=>10,'ident'=>'','complete_time'=>time()]);
                    Db::table('earning')->insert(['order_id'=>$order_id,'uid'=>$uid,'money'=>$order['express_get_money'],'time'=>time(),'type'=>'express']);
                    Db::table('user')->where('id',$uid)->setInc('money',$order['express_get_money']);//步长:自增长
                    
                    push(md5($order['uid']),json_encode(['type'=>1,'message'=>'您的订单已完成','parameters'=>$order_id,'status'=>5]));
                    insert_message($order['uid'],'订单提醒','您的订单已完成',5,$order_id);

                    $msg['msg'] = '操作成功';
               // }
               }else{
                $msg['msg'] = '非法操作';
            }
        }
        return json($msg);
    }

    //获取司机信息
    public function get_info()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $msg['state'] = 1;
        $user = Db::table('user')->field('true_name,money,isExpress,business,express_type')->where('id',$uid)->find();
        $info = Db::table('express_check')->field('true_name,true_head')->where(['uid'=>$uid,'status'=>1])->find();
        //$beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
        //$endToday = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
       // $today_order = 0;
       // $today_earning_detail = Db::table('earning')->where(['uid'=>$uid,'time'=>['between',$beginToday.','.$endToday],'type'=>'express'])->select();
//        $today_earning = 0;
//        foreach ($today_earning_detail as $v){
//            $today_order++;
//            $today_earning += $v['money'];
//        }
//        $info['today_order'] = $today_order;
//        $info['today_earning'] = strval($today_earning);
       // $info['express_type'] = Db::table('express_type')->where('id',$user['express_type'])->value('name');
        //$info['true_name']=$user['true_name'];
       // $info['true_name']='';
        if(empty($info['true_name'])){
           $info['true_name']=$user['true_name'];
        }
        $info['money'] = $user['money'];
        $info['business'] = $user['business'];
        $msg['data'] = $info;
        $msg['msg'] = '获取成功';
        return json($msg);
    }
    /*
     * 我的钱包:今日订单量/今日收益:帐户余额
     * ***/
    public function my_wallet(){
     $token=request()->request("token");
     $info=[];
     if(empty($token)){
       $msg['state']=0;
       $msg["msg"]="error:data"; //数据
     }else{
     $uid=token_decode($token); //司机id
     $msg["state"]=1;
     $user["money"]=Db::table("user")->where("uid",$uid)->value("money");
     $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));//今日开始时间
     $endToday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;//今日结束时间
     $today_order=0;
     $today_earning_detail=Db::table("earning")->where(['uid'=>$uid,'time'=>['between',$beginToday.','.$endToday],'type'=>"express",'status'=>1])->select();
     $today_earning=0;
     foreach($today_earning_detail as $k=>$v){
         $today_order++;
         $today_earning+=$v['money'];
     }
     $info["today_order"]=$today_order;//今日订单量
     $info["today_earning"]=$today_earning;//今日收入
     $info["money"]=$user["money"];
     $msg['data']=$info;
     $msg['msg']="success";
     }
     return json($msg);
   }
    /**
     * 提现申请 express/to_lose_money
     * ***/
    public function to_lose_money(){
      $token=request()->request("token");//用户会话凭证
      $uid=token_decode($token);
      $user=Db::table("user")->where('id',$uid)->find();
      $money=$user['money'];
      $msg['state']=0;
      $msg['data']='';
      if($user['losemoney']>0){
         $msg['msg']="您上一个提现处理还未完成,无法再进行提现";
       }else{
          // halt($money);
          if($money<=0||$money<=100){
              $msg['msg']="很抱歉,您的余额不足100提现金额";
          }else{
              $post['uid']=$uid;
              $post['pid']=$user['pid'];
              $post['cid']=$user['cid'];
              $post['aid']=$user['aid'];
              $post['status']=2;//申请提现之后的状态
              $post['type']=$user['express_type'];//酒店或司机 1or2
              $post['truename']=$user['true_name'];
              $post['money']=$user['money']*(1-$user['express_cut']/100);//平台对司机抽成之后的提现金额
              $system_money=$user['money']*($user['express_cut']/100);
              Db::table("system_money")->where(["type"=>1,'id'=>1])->setInc("system_money",$system_money);//总平台看到的金额
              $system=Db::table("system_money")->where('type',2)->select();//地方上所有的情况
              foreach($system as $v){
               $id=$v['id'];
               $system_aid=$v['aid'];
               //判断下system_money是否有地方的aid或id  //木有就插入,有就自增长
               if(empty($id)||$system_aid==''){
                 Db::table("system_money")->insert(['pid'=>$user['pid'],'cid'=>$user['cid'],'aid'=>$user['aid'],'type'=>2,'system_money'=>$system_money]);
                }else{
                 Db::table("system_money")->where(['id'=>$id,'aid'=>$system_aid])->setInc("system_money",$system_money);
                }
              }
             //后台在拒绝的时候别忘自减金额["system_money"]=$system_money setDec();
         
             $post['account']=$user["ali_number"];//提现的支付宝账户
             $post['losttime']=time();
             Db::table("losemoney")->insert($post);
             //更新用户表中余额
             Db::table("user")->where("id",$uid)->update(['money'=>$user['money']-$money,'losemoney'=>$post['money']]);
            $msg['state']=1;
            $msg['msg']="申请提现成功";
           }
       }
       return json($msg);
    }


//    public function losemoney()
//    {
//        $token = request()->request('token');
//        $uid = token_decode($token);
//        $user = Db::table('user')->where('id',$uid)->find();
//        $money = $user['money'];
//        $msg['state'] = 0;
//        $msg['data'] = '';
//        if($user['losemoney'] > 0){
//            $msg['msg'] = '您上一个提现处理还未完成，无法再进行提现';
//        }else{
//            if($user['money'] < $money || $money < 100){
//                $msg['msg'] = '很抱歉，您的余额不足100元或不足提现金额';
//            }else{
//                $post['uid'] = $uid;
//                $post['pid'] = $user['pid'];
//                $post['cid'] = $user['cid'];
//                $post['aid'] = $user['aid'];
//                $post['status'] = 2;
//                $post['type'] = 'express';
//                $post['truename'] = $user['true_name'];
//                $post['account'] = $user['ali_number'];
//                $post['money'] = $user['money'];
//                $post['losttime'] = time();
//                Db::table('losemoney')->insert($post);
//                Db::table('user')->where('id',$uid)->update(['money'=>$user['money']-$money,'losemoney'=>$money]);
//                $msg['state'] = 1;
//                $msg['msg'] = '提现申请成功';
//            }
//        }
//        return json($msg);
//    }

    //获取类型
    public function express_type()
    {
        $token=request()->request("token");
        if(empty($token)){
           $msg['state']=0;
           $msg['msg']="error:data";
        }else{
        $msg['state'] = 1;
        $msg['data'] = Db::table('express_type')->field('id as pid,name')->select();
        $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    //更新订单标识
    public function update_ident()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $ident = request()->request('ident');
        $order_id = request()->request('order_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if(empty($order_id) || empty($ident)){
            $msg['msg'] = '参数错误';
        }else{
            $msg['state'] = 1;
            Db::table('order')->where(['express'=>$uid,'order_id'=>$order_id])->update(['ident'=>$ident]);
            $msg['msg'] = '操作完成';
        }
        return json($msg);
    }

    //加载司机描述
    public function express_type_description()
    {
        $content = '<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><title>认证帮助</title>';
        $data = Db::table('express_type')->select();
        $html = '';
        foreach ($data as $v){
            $html .= $v['description'];
        }
        return $content.$html;
    }

    //获取提现记录
    public function lose_info()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $msg['state'] = 0;
        $msg['data'] = [];
        if(empty($uid)){
            $msg['msg'] = '参数错误';
        }else{
            $msg['state'] = 1;
            $msg['msg'] = '获取成功';
            $fields = 'money,status,losttime';
            $page = !empty(request()->request('page'))?request()->request('page'):1;
            $pagesize = !empty(request()->request('pagesize'))?request()->request('pagesize'):10;
            $msg['data'] = Db::table('losemoney')->field($fields)->where(['uid'=>$uid])->page($page,$pagesize)->order('losttime desc')->select();
        }
        return json($msg);
    }
    //收益列表
    public function get_earning_list()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $page = !empty(request()->request('page')) ? request()->request('page') : 1;
            $pagesize = !empty(request()->request('pagesize')) ? request()->request('pagesize') : 10;
            $msg['data'] = Db::table('earning')->field('order_id,money,time')->where(['uid'=>$uid,'type'=>'express'])->page($page,$pagesize)->order('time desc')->select();
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

//    public function price_discount(){
//        if(!empty($data['discount'])){
//                    $dis_check = Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount'], 'flag' => 0])->find();
//                   if(count($dis_check) == 0){
//                        die('error');
//                    }else{
//                        if ($dis_check['type'] == 'discount'){
//                            if ($data['express_charge'] >= $dis_check['full']) {
//                                $price = ($data['express_charge'] + $data['tip']) - $dis_check['minus'];
//                                $discount_money = $dis_check['minus'];
//                            }else{
//                                $price = $data['express_charge'] + $data['tip'];
//                            }
//                        }elseif ($dis_check['type'] == 'cash') {
//                            $price = ($data['express_charge'] + $data['tip']) - $dis_check['minus'];
//                            $discount_money = $dis_check['minus'];
//                        }elseif ($dis_check['type'] == 'reduced') {
//                            $price = ($data['express_charge'] + $data['tip']) * ($dis_check['minus'] / 10);
//                            $discount_money = $dis_check['minus'] / 10;
//                        }
//                       Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount']])->update(['flag' => 1]);
//                    }
//                 }else{
//                    $price = $data['express_charge'] + $data['tip'];
//               }
//    }

}
